package com.yuyou.fn.common.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @Author: weiwenfeng
 * @Date: 2018/11/30
 * <p>
 * 卓越大数据平台-可视化接口签名工具类
 */
public class ZYBigDataSignatureUtils {

    private static String accesskeySecret = "";

    public static void main(String[] args) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("accesskey_id", "");
        paramsMap.put("accesskey_secret", "");
        paramsMap.put("version", "");
        paramsMap.put("phone", 183885545);
        paramsMap.put("student_name", "测试");
        paramsMap.put("timestamp", new Date().getTime());
        getURL("", paramsMap);
    }

    public static String getURL(String domain, Map<String, Object> paramsMap) {
        if (paramsMap.containsKey("accesskey_secret")) {
            accesskeySecret = (String) paramsMap.get("accesskey_secret");
            //accesskeySecret不参与参数化过程
            paramsMap.remove("accesskey_secret");
        }
        StringBuilder builder = new StringBuilder();
        return builder.append(domain).append("?").append(getParams(paramsMap)).
                append("signature=").append(getSignatrue(paramsMap)).toString();
    }

    public static String getSignatrue(Map<String, Object> paramsMap) {
        String params = getParams(paramsMap) + accesskeySecret;
        String md5String = null;
        try {
            md5String = new String(params.getBytes("UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String signature = DigestUtils.md5Hex(md5String).toUpperCase();
        return signature;
    }

    /**
     * 获取格式为："accesKeyId=idata_api&phone=13802159855&studentName=测试&timeStamp=1543561101&version=v1.1&" 的串
     *
     * @param paramsMap
     * @return
     */
    public static String getParams(Map<String, Object> paramsMap) {
        // 按key升序
        List<Map.Entry<String, Object>> list = new ArrayList<>(paramsMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Object>>() {
            @Override
            public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : list) {
            builder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        return builder.toString();
    }
}
